#include <string>
#include <algorithm>
using namespace std;
/*
 * @lc app=leetcode.cn id=151 lang=cpp
 *
 * [151] 颠倒字符串中的单词
 */

// @lc code=start
class Solution {
public:
    string reverseWords(string s) {
        int m = 0, n = s.size() - 1;
        while (s[n] == ' ') n--;
        while (m < n) {
            char x = s[m]; s[m] = s[n];
            s[n] = x;
            m++; n--;
        }
        int l = 0;
        bool flag = false; int t = -1;
        s.push_back(' ');
        for (int i = 0; i < s.size(); i++) {
            if (s[i] != ' ') { 
                flag = true; 
                if (t == -1) t = i;
            }
            else if (s[i] == ' ' && flag) {
                reverse(s.begin() + l, s.begin() + i);
                l = l + i - t + 1; flag = false; t = -1;
            }
        }
        while (s.back() == ' ') s.pop_back();
        return s;

    }

};
// @lc code=end

